package com.ruoyi.warning.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.warning.domain.http.DSResponse;
import com.ruoyi.warning.domain.http.LDevice;
import com.ruoyi.warning.domain.http.LPort;
import com.ruoyi.warning.domain.http.LService;
import com.ruoyi.warning.service.LibreService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@org.springframework.stereotype.Service
public class LibreNMSApiClient implements LibreService {
    @Value("${deepseek.host}")
    private String host;
    @Value("${librenms.token}")
    private String authToken;
    private String httpPort = "http://172.30.30.86:8000";
    private String dshttp = "http://nbhcit.f3322.org/";

    public Map<String, Object> getRequest(String url, Map<String,String> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建包含参数的 URL
            URIBuilder uriBuilder = new URIBuilder(url);
            // 添加参数
            if(ObjectUtils.isNotEmpty(map)){
                for (Map.Entry<String,String> entry : map.entrySet()) {
                    uriBuilder.addParameter(entry.getKey(), entry.getValue());
                }
            }
//            uriBuilder.addParameter("param1", "value1");
//            uriBuilder.addParameter("param2", "value2");
            // 创建请求对象
            HttpGet request = new HttpGet(uriBuilder.build());

            // 添加请求头
            request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + authToken);
            request.setHeader(HttpHeaders.ACCEPT, "application/json");

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(request)) {

                // 检查状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("HTTP Status Code: " + statusCode);

                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String jsonResponse = EntityUtils.toString(entity, "UTF-8");
                    Map<String,Object> result = new ObjectMapper().readValue(jsonResponse, Map.class);
                    System.out.println("Response Body: " + jsonResponse);
                    System.out.println(result);
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("请求失败: " + e.getMessage());
        }
        return null;
    }

    public Map<String, Object> getRequestRestful(String url, String id) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            url = url + "/" + id;
            // 创建包含参数的 URL
            URIBuilder uriBuilder = new URIBuilder(url);
            // 创建请求对象
            HttpGet request = new HttpGet(uriBuilder.build());

            // 添加请求头
            request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + authToken);
            request.setHeader(HttpHeaders.ACCEPT, "application/json");

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(request)) {

                // 检查状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("HTTP Status Code: " + statusCode);

                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String jsonResponse = EntityUtils.toString(entity, "UTF-8");
                    Map<String,Object> result = new ObjectMapper().readValue(jsonResponse, Map.class);
                    System.out.println("Response Body: " + jsonResponse);
                    System.out.println(result);
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("请求失败: " + e.getMessage());
        }
        return null;
    }

    public Map<String, Object> postRequest(String url, Map<String,String> map){
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建 POST 请求对象
            HttpPost request = new HttpPost(url);

            // 添加请求头
            request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + authToken);
            request.setHeader(HttpHeaders.ACCEPT, "application/json");
            request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

            // 构建请求体参数
            String paramString = map.entrySet().stream()
                    .map(entry -> entry.getKey() + "=" + entry.getValue())
                    .collect(Collectors.joining("&"));
            StringEntity entity = new StringEntity(paramString);
            request.setEntity(entity);

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                // 检查状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("HTTP Status Code: " + statusCode);

                // 获取响应实体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String jsonResponse = EntityUtils.toString(responseEntity, "UTF-8");
                    Map<String,Object> result = new ObjectMapper().readValue(jsonResponse, Map.class);
                    System.out.println("Response Body: " + jsonResponse);
                    System.out.println(result);
                    return result;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("请求失败: " + e.getMessage());
        }
        return null;
    }

    @Override
    public List<LDevice> getAllDevices(){
        Map<String,Object> map = getRequest(httpPort+"/api/v0/devices",null);
        if(ObjectUtils.isEmpty(map)){
            return null;
        }
        // 获取 devices 对象
        Object devicesObj = map.get("devices");
        if (devicesObj instanceof List) {
            List<?> devicesList = (List<?>) devicesObj;
            // 使用 ObjectMapper 将每个元素转换为 Device 对象
            ObjectMapper mapper = new ObjectMapper();
            return devicesList.stream()
                    .filter(device -> device instanceof Map)
                    .map(device -> mapper.convertValue(device, LDevice.class))
                    .collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public LDevice getDeviceDetail(String hostname) throws JsonProcessingException {
        Map<String,Object> map = getRequestRestful(httpPort+"/api/v0/devices",hostname);
        Object obj = map.get("devices");
        System.out.println(obj);
        //obj转成List<Object>
        List<LDevice> list = (List<LDevice>) obj;
        return list.get(0);
    }

    @Override
    public List<LService> getAllServices() {
        Map<String,Object> map = getRequest(httpPort+"/api/v0/services",null);
        if(ObjectUtils.isEmpty(map)){
            return null;
        }
        // 获取 devices 对象
        Object obj = map.get("services");
        System.out.println(obj);
        //obj转成List<Object>
        List<?> list = (List<?>) obj;
        list = (List<?>)list.get(0);
        // 使用 ObjectMapper 将每个元素转换为 Service 对象
        ObjectMapper mapper = new ObjectMapper();
        return list.stream()
                .filter(service -> service instanceof Map)
                .map(service -> mapper.convertValue(service, LService.class))
                .collect(Collectors.toList());
    }

    @Override
    public List<LPort> getAllPorts() {
        Map<String,Object> map = getRequest(httpPort+"/api/v0/ports",null);
        if(ObjectUtils.isEmpty(map)){
            return null;
        }
        // 获取 devices 对象
        Object obj = map.get("ports");
        System.out.println(obj);
        //obj转成List<Object>
        List<?> list = (List<?>) obj;
//                    list = (List<?>)list.get(0);
        // 使用 ObjectMapper 将每个元素转换为 Service 对象
        ObjectMapper mapper = new ObjectMapper();
        return   list.stream()
                .filter(port -> port instanceof Map)
                .map(port -> mapper.convertValue(port, LPort.class))
                .collect(Collectors.toList());

    }

    @Override
    public LPort getPortDetail(String portId) throws JsonProcessingException {
        Map<String,Object> map = getRequestRestful(httpPort+"/api/v0/devices",portId);
        Object obj = map.get("devices");
        System.out.println(obj);
        //obj转成List<Object>
        List<LPort> list = (List<LPort>) obj;
        return list.get(0);
    }

    @Override
    public DSResponse getDSService(String content) throws JsonProcessingException {

        DSResponse dsResponse = new DSResponse();
        content = content.replace("\n"," ");
        System.out.println(content);
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建包含参数的 URL
//            URIBuilder uriBuilder = new URIBuilder(host);
            URIBuilder uriBuilder = new URIBuilder(host);
            // 创建请求对象
            HttpPost request = new HttpPost(uriBuilder.build());
            content="使用专业的语气与我交流： "+content;
            String json = "{\"api_key\": \"haocheng0511\",\"content\": \""+content+"\"}";
            request.setEntity(new StringEntity(json, "UTF-8"));
            // 添加请求头
            request.setHeader(HttpHeaders.ACCEPT, "application/json");
            // 设置 Content-Type 请求头，明确编码格式为 UTF-8
            request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");
            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                // 检查状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("HTTP Status Code: " + statusCode);
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                System.out.println("+++++++++++++++++++++");
                System.out.println("请求参数: " + EntityUtils.toString(request.getEntity(), "UTF-8"));
                System.out.println("请求方法: " + request.getMethod());
                System.out.println("请求 URL: " + request.getURI());
                System.out.println("请求头信息:");
                for (org.apache.http.Header header : request.getAllHeaders()) {
                    System.out.println(header.getName() + ": " + header.getValue());
                }
                System.out.println("参数: " + request.getEntity());
                System.out.println("HTTP Status Code: " + statusCode);
//                System.out.println(EntityUtils.toString(entity, "UTF-8"));
                if (entity != null) {
                    String jsonResponse = EntityUtils.toString(entity, "UTF-8");
                    ObjectMapper mapper = new ObjectMapper();
                    dsResponse = mapper.readValue(jsonResponse, DSResponse.class);
                    System.out.println(dsResponse);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("请求失败: " + e.getMessage());
        }
        return dsResponse;
    }


    public static void main(String[] args) {
        // 替换为你的实际 Token
//        String authToken = "6d375795a36842ec2cd4bbe9109a8c44";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建包含参数的 URL
            URIBuilder uriBuilder = new URIBuilder("http://172.30.30.91");
            // 添加参数，这里以添加 'param1' 和 'param2' 为例
//            uriBuilder.addParameter("state", "1");
//            uriBuilder.addParameter("param2", "value2");
            // 创建请求对象
            HttpPost request = new HttpPost(uriBuilder.build());
            String json = "{\"api_key\": \"haocheng0511\",\"content\": \"随意简短回复我一下\"}";
            request.setEntity(new StringEntity(json, "UTF-8"));
//            Map<String,String> postmap = Map.of("api_key", "haocheng0511","content","全光网与以太网之间的差别");

            // 构建请求体参数
//            String paramString = postmap.entrySet().stream()
//                    .map(entry -> entry.getKey() + "=" + entry.getValue())
//                    .collect(Collectors.joining("&"));
//            StringEntity post = new StringEntity(paramString, "UTF-8");
//            request.setEntity(post);
            // 添加请求头
//            request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + authToken);
            request.setHeader(HttpHeaders.ACCEPT, "application/json");
            // 设置 Content-Type 请求头，明确编码格式为 UTF-8
            request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");
            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(request)) {

                // 检查状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("HTTP Status Code: " + statusCode);

                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String jsonResponse = EntityUtils.toString(entity, "UTF-8");
//                    Response response1 = new ObjectMapper().readValue(jsonResponse, Response.class);
//                    Map<String,Object> map = new ObjectMapper().readValue(jsonResponse, Map.class);
//                    System.out.println("Response Body: " + jsonResponse);
                    ObjectMapper mapper = new ObjectMapper();
                    DSResponse dsResponse = mapper.readValue(jsonResponse, DSResponse.class);
//                    DSResponse dsResponse = (DSResponse) res.get("data");
//                    System.out.println(res);
//                    System.out.println(res.get("status"));
//                    System.out.println(res.get("data"));
                    System.out.println(dsResponse.getData().getResponse());
//                    System.out.println(data);
//                    System.out.println(map);
                    // 获取 devices 对象
//                    Object obj = map.get("port");
//                    System.out.println(obj);
//                    //obj转成List<Object>
//                    List<?> list = (List<?>) obj;
//                    ObjectMapper mapper = new ObjectMapper();
//                    LPort LPort = mapper.readValue(mapper.writeValueAsString(list.get(0)), LPort.class);
//                    list = (List<?>)list.get(0);
                    // 使用 ObjectMapper 将每个元素转换为 Service 对象
//                    ObjectMapper mapper = new ObjectMapper();
//                    List<Device> ports = list.stream()
//                            .filter(port -> port instanceof Map)
//                            .map(port -> mapper.convertValue(port, Device.class))
//                            .collect(Collectors.toList());
//                    System.out.println(ports);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("请求失败: " + e.getMessage());
        }
    }


}
